﻿using System.Collections.Generic;
using System.Linq;
using Authorization;
using Bussiness;
using Bussiness.Mangement;
using Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Commons;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using System.IO;

namespace NetCoreAPI.Controllers.Portal
{
    /// <summary>
    /// 附件
    /// </summary>
    [ApiController]
    public class AttachmentController : PortalApiController
    {

        private readonly IWebHostEnvironment _webHostEnvironment;
        public AttachmentController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
            Current.ServerPath = _webHostEnvironment.ContentRootPath;
        }

        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ActionResult DownLoadAttachment(int id) {
            var attachment = ServiceHelp.GetAttachmentService.GetById(id);
            if (attachment != null)
            {
                using (var sw = new FileStream(Current.ServerPath + attachment.Path, FileMode.Open))
                {
                    byte[] bytes = new byte[sw.Length];
                    sw.Read(bytes, 0, bytes.Length);
                    sw.Close();
                    // 把 byte[] 转换成 Stream 
                    Stream stream = new MemoryStream(bytes);
                    return File(stream, attachment.ContentType, attachment.Name);
                }
            }
            else
            {
                return new JsonResult(HttpResult.Success(HttpResultCode.SelectFail, "未查询到附件", null));
            }
        }

        /// <summary>
        /// 返回附件信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public ActionResult GetAttachment(int id)
        {
            var attachment = ServiceHelp.GetAttachmentService.GetById(id);
            if (attachment != null)
            {
                return PhysicalFile(Current.ServerPath + attachment.Path, attachment.ContentType);
            }
            else
            {
                return new JsonResult(HttpResult.Success(HttpResultCode.SelectFail, "未查询到附件", null));
            }
        }
    }
}
